import { Router } from 'express';
import routes from './routes';
import { Token } from '../dbserve';
import config from '../config';
const router = Router();
let userinfo: any = {};
// 跨域
router.use(function (req, res, next) {
  res.header({
    "Access-Control-Allow-Origin": "*",//req.headers.origin,
    "Access-Control-Allow-Method": "GET,POST,PUT,DELETE,OPTIONS",
    "Access-Control-Allow-Credentials": true,
    "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept, token",
    "Access-Control-Max-Age": "10000",
  });
  // 预检请求返回
  if (req.method.toLowerCase() === "options") {
    res.sendStatus(200);
    return;
  }
  next();
})
// 统一输出
router.use(function (req, res, next) {
  function error(code = 500, message = '', data = '') {
    res.status(code).send({ code, message, data })
  }
  function success(data = {}, message = "", code = 200) {
    res.status(200).send({ code, data, message })
  }
  function msg(message = "", code = 200) {
    res.status(200).send({ code, message })
  }
  Object.assign(res, { success, error, msg })
  next()
})
// 权限控制
router.use(async function (req, res, next) {
  try {
    const { token } = req.headers;
    if (!token) throw 'err';
    const TOKEN = new Token('token');
    const data = await TOKEN._getToken({ token });
    if (data.length) userinfo = data[0];
  } catch (error) {
    console.log(error);
  }
  next()
})
routes.forEach(item => {
  const type = item.type ? item.type : 'get';
  router.use('/api/v1/' + item.path, function (req, res: any, next) {
    if (item.path.indexOf('install') === -1 && !config.dbhost) {
      res.msg('当前程序未进行初始化安装，请安装后重试！', 500);
      return;
    }
    if (req.method.toLowerCase() === type.toLowerCase()) {
      if (item.isAuth === false) { item.event(req, res); return; }
      if (!userinfo.id) { res.error(401, '无效登录！'); return; };
      if (userinfo.superAdmin || userinfo.roles.some((e: any) => e.path === item.path)) {
        let obj: any = {};
        let query: any = { ...req.query };
        Object.keys(query).forEach((e: any) => {
          if (/^\d+$/.test(query[e])) obj[e] = Number(query[e]);
          else obj[e] = req.query[e]
        })
        req.query = obj;
        item.event(req, res);
        return
      }
      res.msg('无访问权限！', 403)
    }
    else next();
  })
});
router.use('*', (req, res) => {
  res.status(404).send('无效请求！请检查请求方式或地址')
})
export default router
